package com.chenye.es;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;

/**
 * @Auther:chenye
 * @Data:2018/5/14
 * @Description:
 */

@Configuration
public class EsConfig {
    @Autowired
    private EsProperties esProperties;

    @Bean
    public TransportClient transportClient(){
        TransportClient transportClient = null;

        try {
            // 配置信息
            Settings esSetting = Settings.builder()
                    .put("client.transport.sniff", true)//增加嗅探机制，找到ES集群
                    .put("thread_pool.search.size", Integer.parseInt(esProperties.getPool()))//增加线程池个数，暂时设为5
                    .put("cluster.name","chenye-application")//如果修改了集群名字需要在这里指定，不然会报NoNodeAvailableException: No node available
                    .build();
            //配置信息Settings自定义,下面设置为EMPTY
            transportClient = new PreBuiltTransportClient(esSetting);
            TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(esProperties.getIp()), Integer.valueOf(esProperties.getPort()));
//            TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(esProperties.getIp()), Integer.valueOf(esProperties.getPort()));
//            这里可以添加集群
            transportClient.addTransportAddresses(transportAddress);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return transportClient;
    }

}
